from django.shortcuts import render
from django.conf import settings
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.filters import SearchFilter
from django_filters.rest_framework import DjangoFilterBackend, FilterSet

from iClouds.Permissions import OR, AllPermissions, MyPermissions, BoxPermissions
from iClouds.Authentication import MyJWTAuthentication, BoxJWTAuthentication
from iClouds.mktoken import get_tokens_for_user
from iClouds.apidev import filter_views, has_Random

from mysqldb.header import *

from . import tasks as Task
from .serializers import *

# Create your views here.
# 该视图仅允许盒子验证
class SyncAllinpayPlaceviewsListSetViewSet(viewsets.ModelViewSet):
    __title__ = "上传场所视图列表"
    __group__ = "场所数据同步"
    __info__ = {"post": "上传视图列表"}
    __doc__ = """
    create:\n
    <h4>上传视图列表</h4>
    """
    http_method_names = ["post"]
    authentication_classes = [BoxJWTAuthentication]
    permission_classes = [BoxPermissions]
    serializer_class = AllinpayPlaceviewsCreatSerializer
    queryset = AllinpayPlaceviewsList.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 取数据
        name = serializer.data.get("name")
        info = serializer.data.get("info")
        act = serializer.data.get("act")
        # group = serializer.data.get("group")
        try:
            sess = AllinpayPlaceviewsList.objects.get(name=name, act=act)
        except BaseException as err:
            res = AllinpayPlaceviewsList(**serializer.data)
            res.save()
        else:
            res, faq = AllinpayPlaceviewsList.objects.update_or_create(
                defaults=serializer.data, id=sess.id
            )
        return Response({"rescode": 200, "resmsg": serializer.data})


class SyncAllinpayHardwareListSetViewSet(viewsets.ModelViewSet):
    __title__ = "上传场所硬件详情"
    __group__ = "场所数据同步"
    __info__ = {"post": "上传场所硬件详情", "patch": "上传场所硬件变更", "delete": "上传移除场所硬件变更"}
    __doc__ = """
    create:\n
    <h4>上传场所硬件详情</h4>
    partial_update:\n
    <h4>上传场所硬件变更</h4>
    delete:\n
    <h4>移除场所硬件变更</h4>
    """
    http_method_names = ["post", "patch", "delete"]
    authentication_classes = [BoxJWTAuthentication]
    permission_classes = [BoxPermissions]
    serializer_class = AllinpayHardwareListSerializer
    queryset = AllinpayHardwareList.objects.all()

    def create(self, request, *args, **kwargs):
        data = request.data.copy().dict()
        data["localid"] = data.pop("id")
        serializer = self.serializer_class(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save(pid=request.user.id)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def partial_update(self, request, *args, **kwargs):
        try:
            pk = kwargs.get("pk")
            instance = self.queryset.get(localid=pk, pid=request.user.id)
        except BaseException as err:
            data = request.data.copy().dict()
            data["localid"] = data.pop("id")
            instance = self.serializer_class(data=data)
            instance.is_valid(raise_exception=True)
            instance.save(pid=request.user.id)
        else:
            partial = True
            serializer = self.get_serializer(
                instance, data=request.data, partial=partial
            )
            serializer.is_valid(raise_exception=True)
            serializer.save()
        return Response({"rescode": 200, "resmsg": "SUCCESS"})

    def destroy(self, request, *args, **kwargs):
        pk = kwargs.get("pk")
        instance = self.queryset.get(localid=pk, pid=request.user.id)
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class SyncAllinpayMemberListViewSet(viewsets.ModelViewSet):
    __title__ = "上传会员基础信息"
    __group__ = "场所数据同步"
    __info__ = {"post": "上传创建场所会员", "patch": "上传编辑会员基础信息"}
    __doc__ = f"""
    create:\n
    <h4>创建会员基础信息</h4>
    partial_update:\n
    <h4>编辑会员基础信息</h4>
    """
    http_method_names = ["post", "patch"]
    authentication_classes = [BoxJWTAuthentication]
    permission_classes = [BoxPermissions]
    serializer_class = AllinpayMemberListSerializer
    queryset = AllinpayMemberList.objects.all()

    def create(self, request, *args, **kwargs):
        data = request.data.copy().dict()
        data["localid"] = data.pop("id")
        serializer = self.serializer_class(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save(pid=request.user.id)

        # 创建会员积分
        AllinpayInterList(
            id=serializer.data["id"], integral=0, lasttime=timezone.now()
        ).save()
        # 创建会员余额
        AllinpayMoneyList(
            id=serializer.data["id"], integral=0, lasttime=timezone.now()
        ).save()

        return Response({"rescode": 200, "resmsg": serializer.data})

    def partial_update(self, request, *args, **kwargs):
        try:
            pk = kwargs.get("pk")
            instance = self.queryset.get(localid=pk, pid=request.user.id)
        except BaseException as err:
            data = request.data.copy().dict()
            data["localid"] = data.pop("id")
            instance = self.serializer_class(data=data)
            instance.is_valid(raise_exception=True)
            instance.save(pid=request.user.id)
        else:
            partial = True
            serializer = self.get_serializer(
                instance, data=request.data, partial=partial
            )
            serializer.is_valid(raise_exception=True)
            serializer.save()
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class SyncAllinpayCallmeListViewSet(viewsets.ModelViewSet):
    __title__ = "上传呼叫信息"
    __group__ = "场所数据同步"
    __info__ = {"post": "上传创建呼叫信息", "patch": "上传编辑呼叫信息"}
    __doc__ = f"""
    create:\n
    <h4>上传创建呼叫信息</h4>
    partial_update:\n
    <h4>上传编辑呼叫信息</h4>
    """
    http_method_names = ["post", "patch"]
    authentication_classes = [BoxJWTAuthentication]
    permission_classes = [BoxPermissions]
    serializer_class = AllinpayCallmeListSerializer
    queryset = AllinpayCallmeList.objects.all()

    def create(self, request, *args, **kwargs):
        data = request.data.copy().dict()
        data["localid"] = data.pop("id")
        serializer = self.serializer_class(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save(pid=request.user.id)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def partial_update(self, request, *args, **kwargs):
        try:
            pk = kwargs.get("pk")
            instance = self.queryset.get(localid=pk, pid=request.user.id)
        except BaseException as err:
            data = request.data.copy().dict()
            data["localid"] = data.pop("id")
            instance = self.serializer_class(data=data)
            instance.is_valid(raise_exception=True)
            instance.save(pid=request.user.id)
        else:
            partial = True
            serializer = self.get_serializer(
                instance, data=request.data, partial=partial
            )
            serializer.is_valid(raise_exception=True)
            serializer.save()
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class SyncAllinpayStaffinterListViewSet(viewsets.ModelViewSet):
    __title__ = "上传员工积分"
    __group__ = "场所数据同步"
    __info__ = {"patch": "上传员工积分"}
    __doc__ = f"""
    partial_update:\n
    <h4>上传员工积分</h4>
    """
    http_method_names = ["patch"]
    authentication_classes = [BoxJWTAuthentication]
    permission_classes = [BoxPermissions]
    serializer_class = AllinpayStaffinterListSerializer
    queryset = AllinpayStaffinterList.objects.all()

    def partial_update(self, request, *args, **kwargs):
        # print(request.data.copy().dict())
        try:
            pk = kwargs.get("pk")
            instance = self.queryset.get(id=pk)
        except BaseException as err:
            data = request.data.copy().dict()
            data["id"] = kwargs.get("pk")
            instance = self.serializer_class(data=data)
            instance.is_valid(raise_exception=True)
            instance.save()
        else:
            partial = True
            serializer = self.get_serializer(
                instance, data=request.data, partial=partial
            )
            serializer.is_valid(raise_exception=True)
            serializer.save()
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class SyncAllinpayStaffinterLogViewSet(viewsets.ModelViewSet):
    __title__ = "上传员工积分记录"
    __group__ = "场所数据同步"
    __info__ = {"post": "上传员工积分记录"}
    __doc__ = f"""
    create:\n
    <h4>上传员工积分记录</h4>
    """
    http_method_names = ["post"]
    authentication_classes = [BoxJWTAuthentication]
    permission_classes = [BoxPermissions]
    serializer_class = AllinpayStaffinterLogSerializer
    queryset = AllinpayStaffinterLog.objects.all()

    def create(self, request, *args, **kwargs):
        data = request.data.copy().dict()
        data["localid"] = data.pop("id")
        serializer = self.serializer_class(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})


class SyncAllinpayMemberinterListViewSet(viewsets.ModelViewSet):
    __title__ = "上传会员积分"
    __group__ = "场所数据同步"
    __info__ = {"patch": "上传会员积分"}
    __doc__ = f"""
    partial_update:\n
    <h4>上传会员积分</h4>
    """
    http_method_names = ["patch"]
    authentication_classes = [BoxJWTAuthentication]
    permission_classes = [BoxPermissions]
    serializer_class = AllinpayMemberinterListSerializer
    queryset = AllinpayMemberinterList.objects.all()

    def partial_update(self, request, *args, **kwargs):
        # print(request.data.copy().dict())
        try:
            pk = AllinpayMemberList.objects.get(
                localid=kwargs.get("pk"), pid=request.user.id
            )
        except BaseException as err:
            raise serializers.ValidationError({"member": "会员不存在"})

        try:
            instance = self.queryset.get(id=pk.id)
        except BaseException as err:
            data = request.data.copy().dict()
            data["id"] = pk.id
            instance = self.serializer_class(data=data)
            instance.is_valid(raise_exception=True)
            instance.save()
        else:
            partial = True
            serializer = self.get_serializer(
                instance, data=request.data, partial=partial
            )
            serializer.is_valid(raise_exception=True)
            serializer.save()
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class SyncAllinpayMemberinterLogsViewSet(viewsets.ModelViewSet):
    __title__ = "上传会员积分记录"
    __group__ = "场所数据同步"
    __info__ = {"post": "上传会员积分记录"}
    __doc__ = f"""
    create:\n
    <h4>上传会员积分记录</h4>
    """
    http_method_names = ["post"]
    authentication_classes = [BoxJWTAuthentication]
    permission_classes = [BoxPermissions]
    serializer_class = AllinpayMemberinterLogsSerializer
    queryset = AllinpayMemberinterLogs.objects.all()

    def create(self, request, *args, **kwargs):
        data = request.data.copy().dict()
        data["localid"] = data.pop("id")
        serializer = self.serializer_class(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save(pid=request.user.id)
        return Response({"rescode": 200, "resmsg": serializer.data})


class SyncAllinpayMembermoneyListViewSet(viewsets.ModelViewSet):
    __title__ = "上传会员钱包"
    __group__ = "场所数据同步"
    __info__ = {"patch": "上传会员钱包"}
    __doc__ = f"""
    partial_update:\n
    <h4>上传会员钱包</h4>
    """
    http_method_names = ["patch"]
    authentication_classes = [BoxJWTAuthentication]
    permission_classes = [BoxPermissions]
    serializer_class = AllinpayMembermoneyListSerializer
    queryset = AllinpayMembermoneyList.objects.all()

    def partial_update(self, request, *args, **kwargs):
        # print(request.data.copy().dict())
        try:
            pk = AllinpayMemberList.objects.get(
                localid=kwargs.get("pk"), pid=request.user.id
            )
        except BaseException as err:
            raise serializers.ValidationError({"member": "会员不存在"})

        try:
            instance = self.queryset.get(id=pk.id)
        except BaseException as err:
            data = request.data.copy().dict()
            data["id"] = pk.id
            instance = self.serializer_class(data=data)
            instance.is_valid(raise_exception=True)
            instance.save()
        else:
            partial = True
            serializer = self.get_serializer(
                instance, data=request.data, partial=partial
            )
            serializer.is_valid(raise_exception=True)
            serializer.save()
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class SyncAllinpayMembermoneyLogsViewSet(viewsets.ModelViewSet):
    __title__ = "上传会员钱包记录"
    __group__ = "场所数据同步"
    __info__ = {"post": "上传会员钱包记录"}
    __doc__ = f"""
    create:\n
    <h4>上传会员钱包记录</h4>
    """
    http_method_names = ["post"]
    authentication_classes = [BoxJWTAuthentication]
    permission_classes = [BoxPermissions]
    serializer_class = AllinpayMembermoneyLogsSerializer
    queryset = AllinpayMembermoneyLogs.objects.all()

    def create(self, request, *args, **kwargs):
        data = request.data.copy().dict()
        data["localid"] = data.pop("id")
        serializer = self.serializer_class(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save(pid=request.user.id)
        return Response({"rescode": 200, "resmsg": serializer.data})


class SyncWechatTemplateViewSet(viewsets.ModelViewSet):
    """微信公众号模板消息请求"""

    __title__ = "上传微信公众号模板消息请求"
    __group__ = "场所数据同步"
    __info__ = {"post": "上传微信公众号模板消息请求"}
    __doc__ = f"""
    create:\n
    <h4>上传微信公众号模板消息请求</h4>
    """
    http_method_names = ["post"]
    authentication_classes = [BoxJWTAuthentication]
    permission_classes = [BoxPermissions]
    serializer_class = SyncWechatTemplateSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 发送公众号消息
        Task.WeChat_Template_Message(serializer.data)
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayPlaceVersionViewSet(viewsets.ModelViewSet):
    __title__ = "收集场所端版本"
    __group__ = "场所数据同步"
    __info__ = {"get": "场所端版本列表", "post": "收集场所端版本"}
    __doc__ = f"""
    list:\n
    <h4>场所端版本</h4>
    retrieve:\n
    <h4>场所端版本详情</h4>
    create:\n
    <h4>收集场所端版本</h4>
    """
    http_method_names = ["get", "post"]
    authentication_classes = [BoxJWTAuthentication]
    permission_classes = [BoxPermissions]
    serializer_class = AllinpayPlaceVersionSerializer
    queryset = AllinpayPlaceList.objects.all()

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(currenttime=timezone.now())
        return Response({"rescode": 200, "resmsg": serializer.data})
